package com.ruoyi.web.controller.post.controller;

import java.util.ArrayList;
import java.util.List;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.web.controller.post.domain.Post;
import com.ruoyi.web.controller.post.domain.PostComment;
import com.ruoyi.web.controller.post.domain.PostFavorite;
import com.ruoyi.web.controller.post.domain.PostTag;
import com.ruoyi.web.controller.post.domain.PostReport;
import com.ruoyi.web.controller.post.service.IPostCommentService;
import com.ruoyi.web.controller.post.service.IPostFavoriteService;
import com.ruoyi.web.controller.post.service.IPostService;
import com.ruoyi.web.controller.post.service.IPostTagService;
import com.ruoyi.web.controller.post.mapper.PostReportMapper;

import java.util.HashMap;
import java.util.Map;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;

/**
 * 帖子信息操作处理
 * 
 * @author thunderhub
 */
@RestController
@RequestMapping("/post")
public class PostController extends BaseController
{
    @Autowired
    private IPostService postService;
    
    @Autowired
    private IPostTagService postTagService;
    
    @Autowired
    private IPostCommentService postCommentService;
    
    @Autowired
    private IPostFavoriteService postFavoriteService;
    
    @Autowired
    private PostReportMapper postReportMapper;

    /**
     * 获取帖子列表
     */
    @PreAuthorize("@ss.hasPermi('post:post:list')")
    @GetMapping("/list")
    public TableDataInfo list(Post post)
    {
        startPage();
        List<Post> list = postService.selectPostList(post);
        return getDataTable(list);
    }
    
    /**
     * 导出帖子列表
     */
    @PreAuthorize("@ss.hasPermi('post:post:export')")
    @Log(title = "帖子管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Post post)
    {
        List<Post> list = postService.selectPostList(post);
        ExcelUtil<Post> util = new ExcelUtil<Post>(Post.class);
        util.exportExcel(response, list, "帖子数据");
    }

    /**
     * 获取帖子详细信息
     */
    @PreAuthorize("@ss.hasPermi('post:post:query')")
    @GetMapping(value = "/{postId}")
    public AjaxResult getInfo(@PathVariable Long postId)
    {
        Map<String, Object> result = new HashMap<>();
        
        // 更新浏览量
        postService.updatePostViews(postId);
        
        // 获取帖子信息
        Post post = postService.selectPostById(postId);
        if (post == null) {
            return error("帖子不存在");
        }
        result.put("post", post);
        
        // 获取帖子标签
        List<PostTag> tags = postTagService.selectPostTagsByPostId(postId);
        result.put("tags", tags);
        
        // 获取评论，只返回顶级评论，不包含回复
        PostComment commentQuery = new PostComment();
        commentQuery.setPostId(postId);
        commentQuery.setParentId(0L);
        List<PostComment> comments = postCommentService.selectPostCommentList(commentQuery);
        
        // 获取每个评论的回复
        List<Map<String, Object>> commentList = new ArrayList<>();
        for (PostComment comment : comments) {
            Map<String, Object> commentMap = new HashMap<>();
            commentMap.put("comment", comment);
            List<PostComment> replies = postCommentService.selectCommentsByParentId(comment.getCommentId());
            commentMap.put("replies", replies);
            commentList.add(commentMap);
        }
        result.put("comments", commentList);
        
        // 获取相关帖子
        // 1. 同一作者的其他帖子
        List<Post> authorPosts = postService.selectAuthorOtherPosts(post.getAuthorId(), postId, 3);
        result.put("authorPosts", authorPosts);
        
        // 2. 相似标签的帖子
        List<Post> similarPosts = postService.selectSimilarTagsPosts(post.getTags(), postId, 3);
        result.put("similarPosts", similarPosts);
        
        // 判断当前用户是否已收藏
        Long userId = getUserId();
        if (userId != null) {
            PostFavorite favorite = postFavoriteService.selectPostFavoriteByPostIdAndUserId(postId, userId);
            result.put("favorited", favorite != null && "0".equals(favorite.getStatus()));
        } else {
            result.put("favorited", false);
        }
        
        return success(result);
    }

    /**
     * 新增帖子
     */
    @PreAuthorize("@ss.hasPermi('post:post:add')")
    @Log(title = "帖子管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody Post post)
    {
        post.setCreateBy(getUsername());
        post.setAuthorId(getUserId());
        post.setAuthor(getUsername());
        post.setViews(0L);
        post.setComments(0L);
        post.setFavorites(0L);
        
        // 处理标签，如果有传入标签数组
        String tags = post.getTags();
        int result = postService.insertPost(post);
        
        if (result > 0 && StringUtils.isNotEmpty(tags)) {
            // 处理标签关联
            String[] tagArray = tags.split(",");
            for (String tagName : tagArray) {
                // 查询标签是否存在
                PostTag tagQuery = new PostTag();
                tagQuery.setTagName(tagName);
                List<PostTag> existTags = postTagService.selectPostTagList(tagQuery);
                
                Long tagId;
                if (existTags.isEmpty()) {
                    // 创建新标签
                    PostTag newTag = new PostTag();
                    newTag.setTagName(tagName);
                    newTag.setTagColor("blue"); // 默认颜色
                    newTag.setPostCount(1L);
                    newTag.setStatus("0"); // 正常状态
                    newTag.setCreateBy(getUsername());
                    postTagService.insertPostTag(newTag);
                    tagId = newTag.getTagId();
                } else {
                    // 更新标签帖子数量
                    PostTag existTag = existTags.get(0);
                    tagId = existTag.getTagId();
                    postTagService.updatePostTagCount(tagId, 1);
                }
                
                // 创建帖子标签关联
                Long[] tagIds = new Long[]{tagId};
                postTagService.batchInsertPostTagRelation(post.getPostId(), tagIds);
            }
        }
        
        return toAjax(result);
    }

    /**
     * 修改帖子
     */
    @PreAuthorize("@ss.hasPermi('post:post:edit')")
    @Log(title = "帖子管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Post post)
    {
        post.setUpdateBy(getUsername());
        
        // 处理标签
        String tags = post.getTags();
        
        // 先删除旧的标签关联
        postTagService.deletePostTagRelation(post.getPostId());
        
        int result = postService.updatePost(post);
        
        if (result > 0 && StringUtils.isNotEmpty(tags)) {
            // 处理标签关联
            String[] tagArray = tags.split(",");
            for (String tagName : tagArray) {
                // 查询标签是否存在
                PostTag tagQuery = new PostTag();
                tagQuery.setTagName(tagName);
                List<PostTag> existTags = postTagService.selectPostTagList(tagQuery);
                
                Long tagId;
                if (existTags.isEmpty()) {
                    // 创建新标签
                    PostTag newTag = new PostTag();
                    newTag.setTagName(tagName);
                    newTag.setTagColor("blue"); // 默认颜色
                    newTag.setPostCount(1L);
                    newTag.setStatus("0"); // 正常状态
                    newTag.setCreateBy(getUsername());
                    postTagService.insertPostTag(newTag);
                    tagId = newTag.getTagId();
                } else {
                    // 更新标签帖子数量
                    PostTag existTag = existTags.get(0);
                    tagId = existTag.getTagId();
                    postTagService.updatePostTagCount(tagId, 1);
                }
                
                // 创建帖子标签关联
                Long[] tagIds = new Long[]{tagId};
                postTagService.batchInsertPostTagRelation(post.getPostId(), tagIds);
            }
        }
        
        return toAjax(result);
    }

    /**
     * 删除帖子
     */
    @PreAuthorize("@ss.hasPermi('post:post:remove')")
    @Log(title = "帖子管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{postIds}")
    public AjaxResult remove(@PathVariable Long[] postIds)
    {
        // 删除帖子相关的评论和收藏
        for (Long postId : postIds) {
            postCommentService.deletePostCommentByPostId(postId);
            postFavoriteService.deletePostFavoriteByPostId(postId);
            // 删除帖子标签关联
            postTagService.deletePostTagRelation(postId);
        }
        
        return toAjax(postService.deletePostByIds(postIds));
    }
    
    /**
     * 收藏帖子
     */
    @PreAuthorize("@ss.hasPermi('post:post:favorite')")
    @Log(title = "帖子收藏", businessType = BusinessType.INSERT)
    @PostMapping("/favorite/{postId}")
    public AjaxResult favorite(@PathVariable Long postId)
    {
        Long userId = getUserId();
        
        // 检查是否已收藏
        PostFavorite exist = postFavoriteService.selectPostFavoriteByPostIdAndUserId(postId, userId);
        
        if (exist != null) {
            // 已存在记录，检查状态
            if ("0".equals(exist.getStatus())) {
                return error("已收藏该帖子");
            } else {
                // 取消收藏状态，改为收藏状态
                exist.setStatus("0");
                exist.setUpdateBy(getUsername());
                postFavoriteService.updatePostFavorite(exist);
                
                // 更新帖子收藏数量
                postService.updatePostFavorites(postId, 1);
                
                return success("收藏成功");
            }
        } else {
            // 创建收藏记录
            Post post = postService.selectPostById(postId);
            if (post == null) {
                return error("帖子不存在");
            }
            
            PostFavorite favorite = new PostFavorite();
            favorite.setPostId(postId);
            favorite.setUserId(userId);
            favorite.setPostTitle(post.getTitle());
            favorite.setPostCover(post.getCoverImage());
            favorite.setStatus("0");
            favorite.setCreateBy(getUsername());
            postFavoriteService.insertPostFavorite(favorite);
            
            // 更新帖子收藏数量
            postService.updatePostFavorites(postId, 1);
            
            return success("收藏成功");
        }
    }
    
    /**
     * 取消收藏帖子
     */
    @PreAuthorize("@ss.hasPermi('post:post:unfavorite')")
    @Log(title = "取消收藏", businessType = BusinessType.UPDATE)
    @PostMapping("/unfavorite/{postId}")
    public AjaxResult unfavorite(@PathVariable Long postId)
    {
        Long userId = getUserId();
        
        // 检查是否已收藏
        PostFavorite exist = postFavoriteService.selectPostFavoriteByPostIdAndUserId(postId, userId);
        
        if (exist != null && "0".equals(exist.getStatus())) {
            // 更新为取消收藏状态
            exist.setStatus("1");
            exist.setUpdateBy(getUsername());
            postFavoriteService.updatePostFavorite(exist);
            
            // 更新帖子收藏数量
            postService.updatePostFavorites(postId, -1);
            
            return success("取消收藏成功");
        } else {
            return error("未收藏该帖子");
        }
    }
    
    /**
     * 获取用户收藏的帖子列表
     */
    @PreAuthorize("@ss.hasPermi('post:post:list')")
    @GetMapping("/favorite/list")
    public TableDataInfo favoriteList()
    {
        startPage();
        PostFavorite query = new PostFavorite();
        query.setUserId(getUserId());
        query.setStatus("0"); // 只查询收藏状态的记录
        List<PostFavorite> list = postFavoriteService.selectPostFavoriteList(query);
        return getDataTable(list);
    }

    /**
     * 查询待审核帖子列表
     */
    @PreAuthorize("@ss.hasPermi('post:post:review')")
    @GetMapping("/review/list")
    public TableDataInfo reviewList(Post post)
    {
        startPage();
        // 只查询待审核状态的帖子
        post.setStatus("0");
        List<Post> list = postService.selectPostList(post);
        return getDataTable(list);
    }

    /**
     * 审核帖子（通过/拒绝）
     */
    @PreAuthorize("@ss.hasPermi('post:post:review')")
    @Log(title = "帖子审核", businessType = BusinessType.UPDATE)
    @PutMapping("/review/{postId}")
    public AjaxResult reviewPost(@PathVariable Long postId, @RequestBody ReviewRequest request)
    {
        Post post = postService.selectPostById(postId);
        if (post == null) {
            return error("帖子不存在");
        }
        
        Post updatePost = new Post();
        updatePost.setPostId(postId);
        updatePost.setUpdateBy(getUsername());
        
        if ("approve".equals(request.getAction())) {
            updatePost.setStatus("1"); // 审核通过，状态改为已发布
            updatePost.setRemark(request.getReason());
            
            int result = postService.updatePost(updatePost);
            if (result > 0) {
                return success("帖子审核通过");
            } else {
                return error("审核操作失败");
            }
        } else if ("reject".equals(request.getAction())) {
            updatePost.setStatus("2"); // 审核拒绝
            updatePost.setRemark(request.getReason());
            
            int result = postService.updatePost(updatePost);
            if (result > 0) {
                return success("帖子审核拒绝");
            } else {
                return error("审核操作失败");
            }
        } else {
            return error("无效的审核操作");
        }
    }

    /**
     * 强制下架帖子
     */
    @PreAuthorize("@ss.hasPermi('post:post:takedown')")
    @Log(title = "帖子下架", businessType = BusinessType.UPDATE)
    @PutMapping("/takedown/{postId}")
    public AjaxResult takeDownPost(@PathVariable Long postId, @RequestBody TakeDownRequest request)
    {
        Post post = postService.selectPostById(postId);
        if (post == null) {
            return error("帖子不存在");
        }
        
        Post updatePost = new Post();
        updatePost.setPostId(postId);
        updatePost.setStatus("3"); // 状态改为已下架
        updatePost.setRemark(request.getReason());
        updatePost.setUpdateBy(getUsername());
        
        int result = postService.updatePost(updatePost);
        if (result > 0) {
            return success("帖子已下架");
        } else {
            return error("下架操作失败");
        }
    }

    /**
     * 查询举报列表
     */
    @PreAuthorize("@ss.hasPermi('post:post:report')")
    @GetMapping("/report/list")
    public TableDataInfo reportList(PostReport postReport)
    {
        startPage();
        List<PostReport> list = postReportMapper.selectPostReportList(postReport);
        return getDataTable(list);
    }

    /**
     * 处理举报（通过/驳回）
     */
    @PreAuthorize("@ss.hasPermi('post:post:report')")
    @Log(title = "举报处理", businessType = BusinessType.UPDATE)
    @PutMapping("/report/handle/{reportId}")
    public AjaxResult handleReport(@PathVariable Long reportId, @RequestBody ReportHandleRequest request)
    {
        PostReport report = postReportMapper.selectPostReportById(reportId);
        if (report == null) {
            return error("举报记录不存在");
        }
        
        if ("approve".equals(request.getAction())) {
            // 举报属实，下架帖子
            Post post = postService.selectPostById(request.getPostId());
            if (post != null) {
                Post updatePost = new Post();
                updatePost.setPostId(request.getPostId());
                updatePost.setStatus("3"); // 状态改为已下架
                updatePost.setRemark("因举报下架：" + (request.getReason() != null ? request.getReason() : ""));
                updatePost.setUpdateBy(getUsername());
                
                int result = postService.updatePost(updatePost);
                if (result > 0) {
                    // 更新举报记录状态
                    report.setStatus("1"); // 已处理
                    report.setHandleResult("举报属实，帖子已下架");
                    report.setHandleTime(new Date());
                    report.setHandleBy(getUsername());
                    postReportMapper.updatePostReport(report);
                    
                    return success("举报处理成功，帖子已下架");
                } else {
                    return error("处理失败");
                }
            } else {
                return error("帖子不存在");
            }
        } else if ("reject".equals(request.getAction())) {
            // 举报不属实，驳回举报
            report.setStatus("2"); // 已驳回
            report.setHandleResult("举报不属实" + (request.getReason() != null ? "：" + request.getReason() : ""));
            report.setHandleTime(new Date());
            report.setHandleBy(getUsername());
            postReportMapper.updatePostReport(report);
            
            return success("举报已驳回");
        } else {
            return error("无效的处理操作");
        }
    }

    /**
     * 审核请求类
     */
    public static class ReviewRequest {
        private String action;
        private String reason;

        public String getAction() {
            return action;
        }

        public void setAction(String action) {
            this.action = action;
        }

        public String getReason() {
            return reason;
        }

        public void setReason(String reason) {
            this.reason = reason;
        }
    }

    /**
     * 下架请求类
     */
    public static class TakeDownRequest {
        private String reason;

        public String getReason() {
            return reason;
        }

        public void setReason(String reason) {
            this.reason = reason;
        }
    }

    /**
     * 举报处理请求类
     */
    public static class ReportHandleRequest {
        private String action;
        private String reason;
        private Long postId;

        public String getAction() {
            return action;
        }

        public void setAction(String action) {
            this.action = action;
        }

        public String getReason() {
            return reason;
        }

        public void setReason(String reason) {
            this.reason = reason;
        }

        public Long getPostId() {
            return postId;
        }

        public void setPostId(Long postId) {
            this.postId = postId;
        }
    }
} 